package com.example.dbsample.context;

import com.alibaba.ttl.TransmittableThreadLocal;
import org.apache.commons.lang.StringUtils;

import java.util.HashMap;
import java.util.Map;

public class ThreadLocalContext {
    public static final String BUSINESS_LINE = "businessLineCode";
    public static final String USER_UM = "um";

    private static final ThreadLocal<Map<String, Object>> CONTEXT = new ThreadLocal<>();
    private static final TransmittableThreadLocal<Map<String, String>> USER_INFO = new TransmittableThreadLocal<>();

    public static final String USER_ID = "userId";

    public static final String BIZ_CODE = "bizCode";

    public static String getUserInfo(String key) {
        Map<String, String> userInfoMap = USER_INFO.get();
        return userInfoMap == null ? null : userInfoMap.get(key);
    }

    public static void setUserInfo(String key, String value) {
        Map<String, String> userInfoMap = USER_INFO.get();
        if(userInfoMap == null) {
            userInfoMap = new HashMap<>();
        }

        userInfoMap.put(key, value);
        USER_INFO.set(userInfoMap);
    }

    public static void removeUserInfo() {
        USER_INFO.remove();
    }

    private String bizCode;

    public static String getUserId() {
        return getUserInfo(USER_ID);
    }

    public static String getBizCode() {
        return getUserInfo(BIZ_CODE);
    }

    public static Map<String, String> getUserInfo() {
        return USER_INFO.get();
    }

    public static void setBizCode(Map<String, String> userInfo) {
        USER_INFO.set(userInfo);
    }

    public static<V> void setCommonInfo(String key, V value) {
        Map<String, Object> commonInfo = CONTEXT.get();
        if(null == commonInfo) {
            commonInfo = new HashMap<>();
        }
        commonInfo.put(key, value);
        CONTEXT.set(commonInfo);
    }

    public static<V> V getCommonInfo(String key) {
        Map<String, Object> commonInfo = CONTEXT.get();
        if(null == commonInfo) {
            return null;
        }
        return (V) commonInfo.get(key);
    }

    public static String getBusinessLine() {
        return getCommonInfo(BUSINESS_LINE);
    }
    public static void removeCommonInfo() {
        CONTEXT.remove();
    }

    public static String getUserUm() {
        return StringUtils.defaultString(getCommonInfo("um"), "SYS");
    }
}
